//
//  PersonViewController.m
//  Estate
//
//  Created by heyong on 16/5/25.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import <Bugly/Bugly.h>
#import "PersonViewController.h"
#import "ProjectInformationController.h"
#import "PerInfoController.h"
#import "aboutMeViewController.h"
#import "MyDownloadViewController.h"
#import "LoginViewController.h"
#import "SignInRecordViewController.h"
#import "PersonalSettingsViewController.h"

@interface PersonViewController ()
{
    PerInfoController *perCtr;
    //是否显示项目 是否显示我的下载
    BOOL isshowDown;
    // 是否是监理
    BOOL isJianLi;
    // 是否是总监
    BOOL isZongJian;
    // 是否巡检
    BOOL isXunJian;
}

@end

@implementation PersonViewController
- (personIndexView *)indexView {
    if(_indexView==nil){
        _indexView=[[personIndexView alloc]initWithFrame:CGRECTS(0, 0, 375, 603)];
    }
    return _indexView;
}

- (NSArray *)cellArr {
    if(_cellArr==nil){
        _cellArr=[NSArray arrayWithObjects:@"个人信息",@"关于我们",@"个人设置",nil];
    }
    return _cellArr;
}

- (NSArray *)cellArr2 {
    if(_cellArr2==nil){
        _cellArr2=[NSArray arrayWithObjects:@"个人信息",@"关于我们",@"个人设置",@"我的下载",nil];
    }
    return _cellArr2;
}

- (NSArray *)cellArr3 {
    if(_cellArr3==nil){
        _cellArr3=[NSArray arrayWithObjects:@"项目信息",@"关于我们",@"个人设置",@"我的下载",@"个人信息",nil];
    }
    return _cellArr3;
}

- (NSArray *)cellArr4 {
    if(_cellArr4 == nil){
        _cellArr4 = [NSArray arrayWithObjects:@"项目信息",@"个人信息",@"我的下载",@"关于我们",@"签到记录",@"个人设置",nil];
    }
    return _cellArr4;
}
- (NSArray *)cellArr5 {
    if(_cellArr5 == nil){
        _cellArr5 = [NSArray arrayWithObjects:@"个人信息",@"我的下载",@"关于我们",@"签到记录",@"个人设置",nil];
    }
    return _cellArr5;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"个人中心";

    [LSHttpTool checkNetWork:^(NSString *status) {
        if(![status isEqualToString:@"0"]){
            self.isNet=YES;
        }else{
            self.isNet=NO;
        }
        [self setData];

    }];
    
    [self.view addSubview:self.indexView];
    [self.indexView.exitBtn addTarget:self action:@selector(clickBtn) forControlEvents:UIControlEventTouchUpInside];
    self.tableView = self.indexView.tableView;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    //注册通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(setData) name:@"changeHeadImage" object:nil];
    
   }

- (void)setData{
    personModel *model=[[personModel alloc]init];
    model.projectName=DEF_PERSISTENT_GET_OBJECT(@"proname");
    
    //用户名
    NSString *name=DEF_PERSISTENT_GET_OBJECT(@"realname");
    model.name=name;
    
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    if([role isEqualToString:@"USER_01"]){
        role=@"总监";
    }
    
    else if([role isEqualToString:@"USER_03"]){
        role=@"监理员";
    }
    else if([role isEqualToString:@"USER_07"]){
        role=@"专业监理工程师";
    }
    else if([role isEqualToString:@"USER_04"]){
        role=@"监理安全工程师";
    }
    else if([role isEqualToString:@"CONSTRACT_01"]){
        role=@"施工单位项目经理";
    }
    else if([role isEqualToString:@"CONSTRACT_02"]){
        role=@"施工单位总工";
    }
    else if([role isEqualToString:@"CONSTRACT_03"]){
        role=@"施工单位安全总监";
    }
    else if([role isEqualToString:@"CONSTRACT_04"]){
        role=@"施工单位质检员";
    }
    else if([role isEqualToString:@"CONSTRACT_05"]){
        role=@"施工单位安全员";
    }
    else if([role isEqualToString:@"CONSTRACT_06"]){
        role=@"施工单位实验员";
    }
    else if([role isEqualToString:@"CONSTRACT_07"]){
        role=@"施工单位工长";
    }else if([role isEqualToString:@"1"]){
        role=@"巡检组长";
    }else if([role isEqualToString:@"2"]){
        role=@"巡检员";
    }else if([role isEqualToString:@"LEADER_01"]){
        role=@"领导";
    }else if([role isEqualToString:@"BUILD_01"]){
        role=@"建设单位领导";
    }else if ([role isEqualToString:@"BUILD_02"]){
        role=@"建设单位工程部";
    } else if ([role isEqualToString:@"CONSTRACT_08"]) {
        role = @"检查单位实验员";
    }else if([role isEqualToString:@"PROJECT_SUB_LEADER"]){
        role = @"分管领导";
    }
    model.position=role;
    
    if(self.isNet){
        //得到头像
        NSMutableDictionary *parame=[NSMutableDictionary dictionary];
        [parame setValue:USERID forKey:@"userId"];
        [LSHttpTool Post:URL_HEADPHOTO_SELECT parameters:parame success:^(id responseObject){
            NSLog(@"个人信息：%@/nmsg:%@",responseObject,responseObject[@"msg"]);
            if([responseObject[@"code"]isEqualToString:@"1"]){
                NSDictionary *dic=responseObject[@"data"];
                model.headImagePath=dic[@"headUrl"];
                //记录头像URL
                DEF_PERSISTENT_SET_OBJECT(dic[@"headUrl"], @"headImage");
                self.headUrl=dic[@"headUrl"];
                self.indexView.model=model;
                
            }else{
                self.indexView.model=model;
                
            }
        } failure:^(NSError *error) {
            NSLog(@"error:%@",error);
            self.indexView.model=model;
        }];

    }else{
        self.indexView.model=model;

    }
    perCtr=[[PerInfoController alloc]init];
    perCtr.role=role;
    
   
    if([role isEqualToString:@"领导"]|| [role isEqualToString:@"分管领导"]){
        isshowDown = NO;
    }else{
        isshowDown = YES;
    }
    
    if([role isEqualToString:@"巡检组长"]||[role isEqualToString:@"巡检员"] ){
        isXunJian = YES;
    }else{
        isXunJian = NO;
    }
    
    if ([role isEqualToString:@"总监"]) {
        isZongJian = YES;
    } else if ([role isEqualToString:@"监理员"]||[role isEqualToString:@"专业监理工程师"]) {
        isJianLi = YES;
    }
}

#pragma mark -退出登录
- (void)clickBtn{
    // 判断当前项目是否签到签退。如果是允许切换项目
    BOOL qiehuan=[LSUtility projectChangingBySignIn];
    if (qiehuan) {
        
        self.isNet=[LSHttpTool reachability];
      
        if (!self.isNet) {
                [LSUtility showAlertWithMessage:@"当前网络异常,现在退出的话会导致数据丢失或者异常,确定要退出吗?" ok:^{
                    [self logout:YES];
                    return ;
                } cancel:^{
                    return ;
                }];
                
            }else{
                // 强制同步
                DataSynchronization *data=[[DataSynchronization alloc]init];
                [data syncDataFromTable:self.view refresh:NO isNet: self.isNet andExit:YES];
                
                data.blockSyncOver = ^{
                    NSString *userName=DEF_PERSISTENT_GET_OBJECT(@"loginUserss");
                    NSString *deviceId=DEF_PERSISTENT_GET_OBJECT(@"deviceId");
                    [LSHttpTool checkNetWork:^(NSString *status) {
                        if([status isEqualToString:@"0"]){
                            [LSUtility showToastWithMessage:@"网络未连接，同步失败。" inView:kKeyWindow Andtime:1.5];
                            [self logout:YES];
                        }else{
                            if(userName&&deviceId){
                                [LSHttpTool PostExit:URL_LOGIN parameters:@{@"username":userName,@"phoneId":deviceId,@"loginState":@"false"} success:^(id responseObject) {
                                    NSLog(@"退出登录：%@",responseObject);
                                    [self logout:NO];

                                } failure:^(NSError *error) {
                                    [LSUtility showToastWithMessage:@"服务器异常，同步失败。" inView:kKeyWindow Andtime:1.5];
                                    [self logout:YES];

                                }];
                            }else{
                                [LSUtility showToastWithMessage:@"同步失败。" inView:kKeyWindow Andtime:1.5];
                                [self logout:YES];
                            }
                        }
                    }];
                };
           }
        
    }else{
        [LSUtility showToastWithMessage:@"您未签退，请先签退。" inView:self.view Andtime:1.5];
    }
}
-(void)logout:(BOOL)isShow{
    [[UIApplication sharedApplication] cancelAllLocalNotifications];

    LoginViewController *loginCtr=[[LoginViewController alloc]init];
    loginCtr.isShow = isShow;
    DEF_PERSISTENT_REMOVE(@"role");
    DEF_PERSISTENT_REMOVE(@"loginuserPost");
    DEF_PERSISTENT_REMOVE(@"userid");
    DEF_PERSISTENT_REMOVE(@"proid");
    [Bugly reportException:[NSException exceptionWithName:@"退出时上报自定义错误" reason:@"测试" userInfo:@{@"testkey":@"value"}]];
    //记录当前服务器ip
    DEF_PERSISTENT_SET_OBJECT(DEFIP, @"oldServiceIP");
    loginCtr.flag=@"exit";
    [[UIApplication sharedApplication].delegate window].rootViewController=loginCtr;
    // 清除记录的领导
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"isLeader"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark-tableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if(!isshowDown) {
        if (section == 2) {
            return 0.0001;
        }
    } else if (isXunJian) {
        if (section == 4) {
            return 0.0001;
        }
    } else if (isJianLi || isZongJian) {
        if (section == 5) {
            return 0.0001;
        }
    } else {
        if (section == 4) {
            return 0.0001;
        }
    }
    return 10.*BIZ;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if(!isshowDown) {
        return self.cellArr.count;
    } else if (isXunJian) {
        return self.cellArr5.count;
    } else if (isJianLi || isZongJian) {
        return self.cellArr4.count;
    } else {
        return self.cellArr3.count;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.;
}

#pragma mark- tableViewDataSourse
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PersonIndexCell *cell=[tableView dequeueReusableCellWithIdentifier:@"perCell" forIndexPath:indexPath];
    
    NSArray *dataArr;
    if(!isshowDown) {
        dataArr = self.cellArr;
    } else if (isXunJian) {
        dataArr = self.cellArr5;
    } else if (isJianLi || isZongJian) {
        dataArr = self.cellArr4;
    } else {
        dataArr = self.cellArr3;
    }
    cell.title.text=dataArr[indexPath.section];
    cell.iconImg.image = [UIImage imageNamed:dataArr[indexPath.section]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 关于我们
    aboutMeViewController *meCtr = [[aboutMeViewController alloc]init];
    // 个人设置
    PersonalSettingsViewController *psCtr = [[PersonalSettingsViewController alloc]init];
    // 项目信息
    ProjectInformationController *project=[[ProjectInformationController alloc]init];
    // 我的下载
    MyDownloadViewController *downCtr = [[MyDownloadViewController alloc]init];
    
    //判断头像是否为空
    if([self.headUrl isEqualToString:@""]||!self.headUrl){
        NSString *header=DEF_PERSISTENT_GET_OBJECT(@"headImage");
        self.headUrl=header;
    }
    
    if (!isshowDown) {
        if (indexPath.section==0) {
            [self.navigationController pushViewController:perCtr animated:YES];
            perCtr.headUrl=self.headUrl;
        } else if (indexPath.section==1) {
            [self.navigationController pushViewController:meCtr animated:YES];
        } else {
            [self.navigationController pushViewController:psCtr animated:YES];
        }
    } else if (isXunJian) {
       if (indexPath.section == 0) {
            //个人信息
            [self.navigationController pushViewController:perCtr animated:YES];
            perCtr.headUrl=   self.headUrl;
        } else if (indexPath.section == 1) {
            //我的下载
            [self.navigationController pushViewController:downCtr animated:YES];
        } else if (indexPath.section == 2) {
            //关于我们
            [self.navigationController pushViewController:meCtr animated:YES];
        } else if (indexPath.section == 3) {
            //签到记录
            SignInRecordViewController *signInRecordCtr=[[SignInRecordViewController alloc]init];
            [self.navigationController pushViewController:signInRecordCtr animated:YES];
        } else if (indexPath.section == 4) {
            //个人设置
            [self.navigationController pushViewController:psCtr animated:YES];
        }
        
    } else if (isJianLi || isZongJian) {
        if (indexPath.section == 0) {
            //项目信息
            [self.navigationController pushViewController:project animated:YES];
        } else if (indexPath.section == 1) {
            //个人信息
            [self.navigationController pushViewController:perCtr animated:YES];
            perCtr.headUrl=   self.headUrl;
        } else if (indexPath.section == 2) {
            //我的下载
            [self.navigationController pushViewController:downCtr animated:YES];
        } else if (indexPath.section == 3) {
            //关于我们
            [self.navigationController pushViewController:meCtr animated:YES];
        } else if (indexPath.section == 4) {
            //签到记录
            SignInRecordViewController *signInRecordCtr=[[SignInRecordViewController alloc]init];
            [self.navigationController pushViewController:signInRecordCtr animated:YES];
        } else if (indexPath.section == 5) {
            //个人设置
            [self.navigationController pushViewController:psCtr animated:YES];
        }
        
    } else {
        if (indexPath.section == 0) {
            [self.navigationController pushViewController:project animated:YES];
        } else if (indexPath.section == 1) {
            [self.navigationController pushViewController:meCtr animated:YES];
        } else if (indexPath.section == 2) {
            [self.navigationController pushViewController:psCtr animated:YES];
        } else if (indexPath.section == 3) {
            [self.navigationController pushViewController:downCtr animated:YES];
        } else if (indexPath.section == 4) {
            [self.navigationController pushViewController:perCtr animated:YES];
            perCtr.headUrl=   self.headUrl;
        }
    }
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end



